package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlyuan.open.scanner.assembler.ScannerVehicleAssembler;
import com.wlyuan.open.scanner.config.GroupProperties;
import com.wlyuan.open.scanner.dao.entity.CarDO;
import com.wlyuan.open.scanner.dao.mapper.CarMapper;
import com.wlyuan.open.scanner.domain.vehicle.Vehicle;
import com.wlyuan.open.scanner.domain.vehicle.VehicleConvert;
import com.wlyuan.open.scanner.repository.CarRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CarRepositoryImpl implements CarRepository {
    private final CarMapper carMapper;
    private final BaseOrderRepository baseOrderRepository;
    private final GroupProperties groupProperties;

    @Override
    public List<Vehicle> list() {
        logger.info("公司ID > 0");
        List<CarDO> list = carMapper.list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        logger.info("老数据数据量，size：{}", list.size());
        return VehicleConvert.convert(list);
    }

    @Override
    public Vehicle getById(Long carId) {
        return Optional.ofNullable(carId).map(id -> {
            var car = carMapper.selectById(id);
            return Optional.ofNullable(car).map(VehicleConvert::convert).orElse(null);

        }).orElse(null);
    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return carMapper.getByTime(startTime, endTime);
    }

    @Override
    public List<Long> getByTenantIdTime(Long tenantId, String startTime, String endTime) {
        return carMapper.getByTenantIdTime(tenantId, startTime, endTime);
    }

    @Override
    public void getByTenantId(Long tenantId) {
        Optional.ofNullable(tenantId).ifPresent(tenant -> {
            LambdaQueryWrapper<CarDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CarDO::getCarCompanyid, tenant);
            var list = carMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                logger.info("根据租户{}查询车辆数据为0", tenant);
                return;
            }
            logger.info("根据租户{}查询车辆数据为{}", tenant, list.size());
            list.forEach(car -> {
                if (groupProperties.groupTenantList().contains(car.getCarCompanyid())) {
                    car.setCarCreator(0L);
                    car.setCarUpdater(0L);
                }
                var data = VehicleConvert.convert(car);
                baseOrderRepository.sync(ScannerVehicleAssembler.assemble(data));
            });
        });
    }
}
